// import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Modal, Radio, Row, message, Divider } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import MonacoEditor, { RefEditorInstance } from '@uiw/react-monacoeditor';
import { editor } from 'monaco-editor';
import ProCard from '@ant-design/pro-card';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import ReactDiffViewer from 'react-diff-viewer';
import { FormattedMessage, useIntl } from 'umi';
import styles from './index.less';


import { getAppCfgInfo, getAppCfgTemplateInfo, listAppCfgList } from '@/services/configserver/api';

import { parse } from 'url';

const AppCfgDetails: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const intl = useIntl();
  // 设置monacoEditor的 theme code mode
  const editorRef = useRef<RefEditorInstance>(null);
  const [language, setlanguage] = useState('yaml');
  // table 显示的内容
  const [tableListDataSource, setTableListDataSource] = useState<API.AppCfgFileListItem[]>([]);
  // app id,在url里面
  const [appID, setAppID] = useState<number>();
  const [appName, setAppName] = useState<string>();
  // 切换配置文件/模版的内容
  const [cfgInfo, setCfgInfo] = useState<string>('');
  const [cfgTemplateInfo, setCfgTemplateInfo] = useState<string>('');
  // 定义配置显示区的内容
  const [showData, setShowData] = useState<string>('');

  // Diff窗口
  const [showDiffModal, handleDiffModal] = useState<boolean>(false);
  const editorDidMount = (editor: editor.IStandaloneCodeEditor) => {
    // console.log('editorDidMount', editor, monaco); // eslint-disable-line
    editor.focus();
  }
  // Diff 的value
  const [oldValue, setOldValue] = useState<string>('');
  const [newValue, setNewValue] = useState<string>('');

  // const onSelectChange = (value: string) => {
  //   // editorRef.current?.editor.set
  //   const model = editorRef.current?.editor?.getModel()
  //   if (model) {
  //     editor.setModelLanguage(model, value || '');
  //   }
  //   setMode(value);
  // }
  // const onSelectThemeChange = (value: string) => {
  //   setTheme(value);
  // }

  //获取getAppCfgList，注入到表格里
  const getAppCfgList = async () => {
    let param = parse(location.href, true).query;
    const id = Number(param.id);
    // 获取appname
    setAppName(param.appname?.toString());
    setAppID(id);
    try {
      const result = await listAppCfgList({ id });
      setTableListDataSource(result.data)
      // 重新刷新一下数据，保证有数据
      if (result.success) {
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
      console.log('AppCfgDetails event=getAppCfgList,value=', result.data);
      return true;
    } catch (error) {
      setTableListDataSource([]);
      return false;
    }
  }


  //处理onrow点击事件
  const onCfgInfoRowClick = async (fields: API.AppCfgFileListItem) => {

    let config_template_id = fields.id;
    let app_id = appID;
    let configtype = fields.configtype;
    let ext = 'yaml';

    //判断后缀名称
    switch (fields.ext) {
      case 'yml': {
        ext = 'yaml'
        break;
      }
      case "yaml": {
        ext = 'yaml';
        break;
      }
      case "js": {
        ext = 'javascript';
        break;
      }
      case "sh": {
        ext = 'shell';
        break;
      }
      case "sh": {
        ext = 'shell';
        break;
      }
      default: {
        ext = 'yaml';
        break;
      }
    }

    //获取cfg内容
    try {
      const result = await getAppCfgInfo({ app_id, config_template_id, configtype });
      console.log('AppCfgDetails Event=onCfgInfoRowClick.getAppCfgInfo,value=', fields);
      // message.success('配置文件读取成功');
      console.log('AppCfgDetails Event=配置文件读取成功');

      const model = editorRef.current?.editor?.getModel()
      if (model) {
        editor.setModelLanguage(model, ext || '');
      }
      setCfgInfo(result.toString());
      setOldValue(result.toString());
      setShowData(result.toString());
    } catch (error) {
      message.error('配置文件读取失败');
      return false;
    }

    //获取cfg 模版 内容
    try {
      const result = await getAppCfgTemplateInfo({ app_id, config_template_id, configtype });
      console.log('AppCfgDetails Event=onCfgInfoRowClick.getAppCfgTemplateInfo,value=', fields);
      // message.success('配置模版读取成功');
      console.log('AppCfgDetails Event=配置模版读取成功');

      setCfgTemplateInfo(result.toString());

    } catch (error) {
      message.error('配置模版读取失败');
      return false;
    }
    return true;
  };

  useEffect(() => {
    getAppCfgList();
    setlanguage("yaml");
  }, []);

  const columns: ProColumns<API.AppCfgFileListItem>[] = [
    {
      dataIndex: 'index',
      title: 'index',
    },
    {
      dataIndex: 'id',
      title: 'id',
      hideInTable: true,
    },
    {
      dataIndex: 'configname',
      title: 'configname',
    },
    {
      dataIndex: 'ext',
      title: 'ext',
      hideInTable: true,
    },
    {
      dataIndex: 'configtype',
      title: 'configtype',
    },
  ];


  return (
    // <PageContainer>
    <>
      <ProCard split="vertical" ghost gutter={8}>
        <ProCard
          title={intl.formatMessage({
            id: 'pages.appCfgDetails.leftZoneTitle',
            defaultMessage: 'config list',
          })}
          colSpan="30%"
          headerBordered
          bordered
          className={styles.tableFrame}
        >

          <Divider orientation="left" plain>
            应用名称: {appName}
          </Divider>

          <ProTable<API.AppCfgFileListItem>
            columns={columns}
            actionRef={actionRef}
            style={{
              height: 562
            }}
            onRow={record => {
              return {
                onClick: (event) => {
                  // 这里要处理在MonacoEditor里的value值了
                  onCfgInfoRowClick(record);
                }, // 点击行
              };
            }}
            //request={listAppCfgList({ e })}
            request={(params, sorter, filter) => {
              // 表单搜索项会从 params 传入，传递给后端接口。
              console.log(params, sorter, filter);
              return Promise.resolve({
                data: tableListDataSource,
                success: true,
              });
            }}
            rowKey="id"
            pagination={{
              showQuickJumper: true,
            }}
            toolBarRender={false}
            search={false}
          />
        </ProCard>

        <ProCard
          title={intl.formatMessage({
            id: 'pages.appCfgDetails.rightZoneTitle',
            defaultMessage: 'config info',
          })}
          bordered
          headerBordered>
          <Row
            style={{
              paddingBottom: 20
            }}>
            <Col span={8}>
              <Radio.Group
                onChange={(e) => {
                  if (e.target.value === 'configTemplate') {
                    setShowData(cfgTemplateInfo);
                    setOldValue(cfgTemplateInfo);
                  }
                  if (e.target.value === 'configData') {
                    setShowData(cfgInfo);
                    setOldValue(cfgInfo);
                  }
                }}
              >
                <Radio
                  value="configData"
                  checked
                >
                  <FormattedMessage
                    id="pages.appCfgDetails.cfgData"
                    defaultMessage="data"
                  />
                </Radio>

                <Radio
                  value="configTemplate"
                >
                  <FormattedMessage
                    id="pages.appCfgDetails.cfgTemplate"
                    defaultMessage="template"
                  />
                </Radio>
              </Radio.Group>
            </Col>
            <Col span={8} offset={8}>
            </Col>
          </Row>
          <Row
            style={{
              paddingBottom: 10
            }}
          >
            <MonacoEditor
              ref={editorRef}
              language={language}
              height="504px"
              width="100%"
              value={showData}
              editorDidMount={(editor) => editorDidMount(editor)}
              onChange={async (value) => {
                console.log("event = AppCfgDetails.MonacoEditor.onChange,newValue= ", value);
                setNewValue(value);
              }}
              options={{
                theme: 'vs'
              }}
            />
          </Row>
          <Row>
            <Button
              type="primary"
              key="update"
              onClick={() => {
                handleDiffModal(true);
              }}
            >
              <FormattedMessage
                id="pages.appCfgDetails.btn.updatecfg"
                defaultMessage="update"
              />
            </Button>

            <Button
              type="primary"
              key="diff"
              style={
                {
                  marginLeft: 20
                }
              }
              onClick={() => {
                setOldValue(cfgInfo);
                setNewValue(cfgTemplateInfo);
                handleDiffModal(true);
              }}
            >
              <FormattedMessage
                id="pages.appCfgDetails.btn.diffTemplatecfg"
                defaultMessage="diff"
              />
            </Button>
          </Row>

        </ProCard>
      </ProCard>
      <Modal
        title={intl.formatMessage({
          id: 'pages.appCfgDetails.diffModalTitle',
          defaultMessage: 'Diff',
        })}
        visible={showDiffModal}
        width={1600}
        bodyStyle={{
          padding: '10px',
        }}
        onOk={() => {
          handleDiffModal(false);
        }}
        onCancel={() => {
          handleDiffModal(false);
        }}
      >
        <ReactDiffViewer
          oldValue={oldValue}
          newValue={newValue}
          splitView={true}
          showDiffOnly={true}
          extraLinesSurroundingDiff={3}
        />
      </Modal>
      {/* </PageContainer > */}
    </>
  );
};

export default AppCfgDetails;
